package com.dog.basics.common.aspect;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.common.utils.StringUtils;
import com.dog.basics.common.annotation.Limit;
import com.dog.basics.common.enums.LimitType;
import com.dog.basics.common.util.IPHelper;
import com.dog.basics.common.util.RedisUtil;
import com.dog.basics.common.util.SpringContextUtils;
import com.google.common.collect.ImmutableList;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;

import java.lang.reflect.Method;

/**
 * @description: 限流切面
 * @author: He
 * @date: Created in 2020/6/30 10:31
 * @version: 1.0
 * @modified By:
 */
@Aspect
@Configuration
@AllArgsConstructor
@Log4j2
public class LimitLnterceptorAspect {

    private final String REDIS_SCRIPT = buildLuaScript();

    public static void main(String[] args) {
        System.out.println(StringUtils.join("BBCT", "192.168.1.15"));
    }

    @Around("@annotation(limit)")
    public Object interceptor(ProceedingJoinPoint pjp, Limit limit) {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        Limit limitAnno = method.getAnnotation(Limit.class);
        LimitType limitType = limitAnno.limitType();
        String name = limitAnno.name();

        String key = null;
        int limitPeriod = limitAnno.period();
        int limitCount = limitAnno.count();
        switch (limitType) {
            case IP:
                key = IPHelper.getIpAddr();
                break;
            case CUSTOMER:
                // TODO 如果此处想根据表达式或者一些规则生成 请看 一起来学Spring Boot | 第二十三篇：轻松搞定重复提交（分布式锁）
                key = limitAnno.key();
                break;
            default:
                break;
        }
        String joinKey = StringUtils.join(limitAnno.prefix(), key);
        String handleKey = StrUtil.isNotBlank(limitAnno.prefixKey())?StrUtil.format("{}:{}", limitAnno.prefixKey(),joinKey) : joinKey;
        ImmutableList<String> keys = ImmutableList.of(StringUtils.join(limitAnno.prefix(), handleKey));
        try {
            RedisScript<Number> redisScript = new DefaultRedisScript(REDIS_SCRIPT, Number.class);
            Number count = (Number) SpringContextUtils.getBean("limitRedisTemplate", RedisTemplate.class).execute(redisScript, keys, limitCount, limitPeriod);
            log.info("Access try count is {} for name={} and key = {}", count, name, key);
            if(count != null && count.intValue() <= limitCount) {
                return pjp.proceed();
            } else {
                if (StrUtil.isNotBlank(limitAnno.name())){
                    Validator.validateTrue(Boolean.FALSE, "{},请稍后重试!",limitAnno.name());
                }else{
                    Validator.validateTrue(Boolean.FALSE, "业务请求频繁,请稍后重试!");
                }
            }
        } catch (Throwable e) {
            if (e instanceof RuntimeException) {
                Validator.validateTrue(Boolean.FALSE, e.getLocalizedMessage());
            }
            Validator.validateTrue(Boolean.FALSE, "server exception");
        }
        return null;
    }

    /**
     * 限流 脚本
     *
     * @return lua脚本
     */
    private String buildLuaScript() {
        StringBuilder lua = new StringBuilder();
        lua.append("local c")
                .append("\n c = redis.call('get', KEYS[1])")
                // 调用不超过最大值，则直接返回
                .append("\n if c and tonumber(c) > tonumber(ARGV[1]) then")
                .append("\n return c;")
                .append("\n end")
                // 执行计算器自加
                .append("\n c = redis.call('incr', KEYS[1])")
                .append("\n if tonumber(c) == 1 then")
                // 从第一次调用开始限流，设置对应键值的过期
                .append("\n redis.call('expire', KEYS[1], ARGV[2])")
                .append("\n end")
                .append("\n return c;");
        return lua.toString();
    }
}
